package com.ysqcould.allocation.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.oreilly.servlet.multipart.FilePart;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.ysqcould.allocation.domain.WxConfig;
import com.ysqcould.allocation.mapper.WxConfigMapper;
import com.ysqcould.common.core.domain.AjaxResult;
import com.ysqcould.common.oss.MD5Utils;
import com.ysqcould.common.oss.OssClientUtil;
import com.ysqcould.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.UUID;

public class UploadFileUtil {

    // endpoint以杭州为例，其它region请按实际情况填写
    private static final String endpoint ="oss-cn-shenzhen.aliyuncs.com";
    private static final String accessKeyId = "LTAI4GFHDtc6xbFWsQf7hWQc";
    private static final String accessKeySecret = "N0OOTD9NS8cGeMr1dFQUdPFUbk3IMa";
    private static final String bucketName = "shequncloud";
    private static final String floder = "yunshequn-images";
    @Autowired
    private static WxConfigMapper configMapper;

    public static FilePart fileuploads(HttpServletRequest request) {
        boolean flag = false;
        MultipartParser mp;
        try {
            mp = new MultipartParser(request, 52428800*20, false, false, "UTF-8");
            Part part = null;
            int i = 0;
            while ((part = mp.readNextPart()) != null) {
                String name = part.getName();
                if (part.isFile()) {
                    FilePart filePart = (FilePart) part;
                    return filePart;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 调用阿里云OSS sdk
     * @param filePath filePath为在Bucket下的路径
     * @param inputStream
     * @return
     */
    public static String AliOSSUpload(InputStream inputStream, String filePath) {

        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setConnectionTimeout(60 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(60 * 1000);// socket超时，默认15秒
        conf.setMaxConnections(10); // // 设置HTTP最大连接数为10
        conf.setMaxErrorRetry(3);// 失败后最大重试次数

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传,penderie为Bucket名，filePath为在Bucket下的路径，包括文件夹和文件名，imagse/0001.jpg
        ossClient.putObject(bucketName, floder + "/" + filePath, inputStream);
        ossClient.shutdown();
        return "https://" + bucketName + "." + endpoint + "/" + floder + "/" + filePath;

        //设置过期时间为10年
        //Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);

        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        //URL url = ossClient.generatePresignedUrl(bucketName, floder + "/" + filePath, expiration);

        // 关闭client
        //ossClient.shutdown();
        //return url.toString();

    }

    /**
     * 上传图片到阿里云OSS
     */
    public static AjaxResult uploadImageToAliOSS(Integer userId, HttpServletRequest request){

        String fileType = "images";
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("images", "gif,jpg,jpeg,png,bmp");

        FilePart filePart = UploadFileUtil.fileuploads(request);
        String fileExt = filePart.getFileName().substring(filePart.getFileName().lastIndexOf(".") + 1).toLowerCase();

        if (Arrays.<String> asList(extMap.get(fileType).split(",")).contains(fileExt)) {
            //String filePath = filePart.getFileName();
            String realName = UUID.randomUUID().toString().toUpperCase().replace("-", "")+"."+fileExt;
            InputStream inputStream = filePart.getInputStream();
            String fileUrl = UploadFileUtil.AliOSSUpload(inputStream, "wxadmin/" +userId+ "/"+realName);
            return AjaxResult.success("上传成功", fileUrl);
        } else {
            return AjaxResult.error("上传失败", null);
        }
    }

    /**
     * 上传文件到阿里云OSS
     */
    public static String uploadFileToAliOSS(Long userId, MultipartFile file) throws IOException {
        final InputStream inputStream = file.getInputStream();
        final String fileName = file.getOriginalFilename();
        String fileUrl = UploadFileUtil.AliOSSUpload(inputStream, "wxadmin/" + userId + "/" + fileName);
        return fileUrl;
    }

    /**
     * 上传图片到阿里云OSS
     */
    public static String uploadMoreImageToAliOSS(Integer userId, HttpServletRequest request){

        String fileType = "images";
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("images", "gif,jpg,jpeg,png,bmp");

        FilePart filePart = UploadFileUtil.fileuploads(request);
        String fileExt = filePart.getFileName().substring(filePart.getFileName().lastIndexOf(".") + 1).toLowerCase();

        if (Arrays.<String> asList(extMap.get(fileType).split(",")).contains(fileExt)) {
            //String filePath = filePart.getFileName();
            String realName = UUID.randomUUID().toString().toUpperCase().replace("-", "")+"."+fileExt;
            InputStream inputStream = filePart.getInputStream();
            return UploadFileUtil.AliOSSUpload(inputStream, "wxadmin/" +userId+ "/"+realName);
        }
        return null;
    }


    /**
     * 上传网络图片url
     * @param imageUrl          图片地址
     */
    public static String uploadUrlImage(String imageUrl){
        //文件目录
        String fileDir = "ht-images/netImage/";
        String suffix = imageUrl.contains("?wx_fmt=")?"." + imageUrl.substring(imageUrl.lastIndexOf('=') + 1):"";
        try {
            String saveUrl = fileDir+ MD5Utils.getMD5(imageUrl);
            InputStream inputStream = new URL(imageUrl).openStream();
            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            // 上传网络流。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, saveUrl+suffix, inputStream);
            ossClient.putObject(putObjectRequest);
            ossClient.shutdown();
            //图片地址
            return "https://"+bucketName+"."+endpoint+"/"+saveUrl+suffix;
        }catch (Exception e){
            String.format("图片流异常：%s",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传分享图片URL(红底海报图)
     * @param url           图片url
     * @param rqUrlDate     二维码的url
     * @param name          慈善名称
     * @param title         标题
     * @param money         目标金额
     * @param asName        协会名称
     * @param ioc           协会的公众号商标
     * @throws IOException  异常
     */
    public static String postUrlOssUpload(Integer userId,String url,String rqUrlDate,String name, String title,Integer money,
                                          String asName,String ioc,String bottomUrl,int pixel) throws IOException {
        ioc = ioc+"?x-oss-process=image/resize,m_fill,h_124,w_124/circle,r_124/format,png";
        //bottomUrl = StringUtil.isEmpty(bottomUrl)?bottomUrl:"https://shequncloud.oss-cn-shenzhen.aliyuncs.com/ht-images/test/graciousnessTheGuilds.png";
        String targetMoney = "目标金额 ￥"+new BigDecimal(new Double(money)/100).setScale(2,BigDecimal.ROUND_HALF_UP);
        String content = "长按或扫描识别二维码";
        name = name.length()>19?name.substring(0,19)+"...":name;
        title = title.length()>21?title.substring(0,21)+"...":title;
        final BufferedImage qrCodeImage = QrCodeUtil.generate(rqUrlDate, 90, 90);

        int width = 750;
        int height = 1334;
        BufferedImage bgBufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// RGB形式
        Graphics2D bgBufImageGraphics = bgBufImage.createGraphics();
        bgBufImageGraphics.setBackground(Color.WHITE);// 设置背景色
        bgBufImageGraphics.clearRect(0, 0, width, height);// 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。

        // bgBufImageGraphics.setBackground(new Color(255,255,255));
        bgBufImageGraphics.setPaint(Color.black);// 设置画笔,设置Paint属性
        Font font = new Font("宋体", Font.BOLD, 20);
        bgBufImageGraphics.setFont(font);
        // 抗锯齿
        bgBufImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        BufferedImage bottomBufImage = ImageIO.read(new URL(bottomUrl));
        BufferedImage iocBufImage = ImageIO.read(new URL(ioc));
        BufferedImage posterBufImage = ImageIO.read(new URL(url));
        int widthX = 58;

        bgBufImageGraphics.drawImage(bottomBufImage, 0, 0, 750, 1334, null);

        font = new Font("宋体", Font.BOLD, 35);
        bgBufImageGraphics.setFont(font);
        bgBufImageGraphics.setPaint(Color.WHITE);// 设置画笔,设置Paint属性

        //计算字体长度后居中
        FontMetrics fm = bgBufImageGraphics.getFontMetrics(font);
        int textWidth = fm.stringWidth(asName);
        int wX = (width - textWidth) / 2;
        bgBufImageGraphics.drawString(asName, wX, 240);
        if(pixel==0){
            font = new Font("宋体", Font.BOLD, 25);
            bgBufImageGraphics.setFont(font);
            bgBufImageGraphics.setPaint(Color.RED);// 设置画笔,设置Paint属性
            bgBufImageGraphics.drawString(targetMoney, widthX, 960);
        }
        bgBufImageGraphics.setPaint(Color.BLACK);
        font = new Font("宋体", Font.BOLD, 22);
        bgBufImageGraphics.setFont(font);
        bgBufImageGraphics.drawString(name, widthX, 1000-pixel);

        font = new Font("宋体", Font.PLAIN, 20);
        bgBufImageGraphics.setFont(font);
        bgBufImageGraphics.drawString(title, widthX, 1030-pixel);


        font = new Font("宋体", Font.PLAIN, 22);
        Color color     = new Color(100, 100, 100);
        bgBufImageGraphics.setPaint(color);
        bgBufImageGraphics.setFont(font);
        bgBufImageGraphics.drawString(content, widthX, 1070-pixel);


        bgBufImageGraphics.drawImage(iocBufImage, 315, 58, 124, 124, null);
        bgBufImageGraphics.drawImage(posterBufImage, 45, 558, 660, 370, null);
        bgBufImageGraphics.drawImage(qrCodeImage, 550, 935, 140, 140, null);
        bgBufImageGraphics.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(bgBufImage, "png", os);
        }catch (Exception e){
            os.close();
            e.printStackTrace();
        }
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        String postUrl = OssClientUtil.uploadPictures(userId+"charity" + System.currentTimeMillis() + ".png", input);
        input.close();
        os.close();
        return postUrl;
    }
    /**
     * 上传分享图片URL（绿底支付图）
     * @param url           底图url
     * @param charityName   捐赠项目名称
     * @param rqUrlDate     二维码的url
     * @param userId        用户ID
     */
    public static String postUrlOssUpload(String url,String charityName,String rqUrlDate,Integer userId) throws IOException{
        url = StringUtils.isEmpty(url)?"https://shequncloud.oss-cn-shenzhen.aliyuncs.com/ht-images/test/43generationCharityPayLink.png":url;
        int width = 750;
        int height = 1334;
        BufferedImage bgBufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// RGB形式
        Graphics2D bgBufImageGraphics = bgBufImage.createGraphics();
        bgBufImageGraphics.setBackground(Color.WHITE);// 设置背景色
        bgBufImageGraphics.clearRect(0, 0, width, height);// 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
        bgBufImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        BufferedImage bottomBufImage = ImageIO.read(new URL(url));
        bgBufImageGraphics.drawImage(bottomBufImage, 0, 0, width, height, null);
//
//        rqUrlDate = "https://www.shequncloud.com/wxapp/?";
//        StringBuilder sb = new StringBuilder(rqUrlDate);
//        sb.append("asId=").append(111)
//                .append("&appId=").append("wx345df9aa0ab93986")
//                .append("#/pages/donateCenter/detail?")
//                .append("pId=").append(102);
//        rqUrlDate = sb.toString();
        final BufferedImage qrCodeImage = QrCodeUtil.generate(rqUrlDate, 340, 340);
        bgBufImageGraphics.drawImage(qrCodeImage, 206, 463, 340, 340, null);

        Font font = new Font("黑体", Font.BOLD, 20);
        bgBufImageGraphics.setFont(font);
        bgBufImageGraphics.setPaint(new Color(55, 55, 55));// 设置画笔,设置Paint属性
        FontMetrics fm = bgBufImageGraphics.getFontMetrics(font);
        charityName = "项目:"+charityName;
        charityName = charityName.length()>14?charityName.substring(0,14)+"..":charityName;
        int textWidth = fm.stringWidth(charityName);
        int wX = (width - textWidth) / 2;
        bgBufImageGraphics.drawString(charityName, wX, 883);
        bgBufImageGraphics.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(bgBufImage, "png", os);
        }catch (Exception e){
            os.close();
            e.printStackTrace();
        }
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        String postUrl = OssClientUtil.uploadPictures(userId+"charityPayLink" + System.currentTimeMillis() + ".png", input);
        input.close();
        os.close();
        return postUrl;
    }
}
